package io.bluerain.g4_tools.ui.item;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.litesuits.common.utils.ShellUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import io.bluerain.g4_tools.R;
import io.bluerain.g4_tools.entities.Index;
import io.bluerain.g4_tools.entities.ResourceInfo;
import io.bluerain.g4_tools.utils.FileUtils;
import io.bluerain.g4_tools.utils.JsonUtils;
import io.bluerain.g4_tools.utils.Zip;
import io.bluerain.ldrawersample.ItemFragment;

/**
 * Created by foredawn on 15-9-23.
 * 输入谷歌服务功能
 */
public class GmsFragment extends ItemFragment {

    static String CONF_PATH;
    static String CONF_NAME = ".g4_tools";
    static String TEMP_DIR;
    static String INDEX_FILE = "index.json";

    static int WHAT_EDIT_INFO = 0x1;

    private Index index;
    EditText editPathInfo;
    TextView txtPagInfo, linkAbout, linkUpdate, txtCurrentVersion;
    Handler handler;

    @Override
    public void findRoot(View root) {
        initVar();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        InputStream is = null;
        if (resultCode == getActivity().RESULT_OK) {
            try {
                is = getActivity().getContentResolver().openInputStream(data.getData());
                //处理文件流(解压到SD卡配置目录)
                TEMP_DIR = FileUtils.createDirOnSDCard(CONF_NAME + "/temp", true);//创建临时文件夹(存在则删除)
                Zip.UnZipFolder(is, CONF_PATH + "/temp"); //解压到临时文件夹
                readTempDir();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    View.OnClickListener onSelectFileListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectFile(v);
        }
    };

    public void selectFile(View source) {
        Intent intent = new Intent();
        intent.setType("application/octet-stream");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 1);
    }

    public void start(View source) {
        if (editPathInfo.getHint().equals(getResources().getString(R.string.hint_file))) {
            Toast.makeText(getActivity(), "请选择刷入包", Toast.LENGTH_SHORT).show();
            return; //如果未选择文件不进行操作
        }
        //"mkdir -p " + resource.getTarget()
        String[] createDirCmdList = new String[index.getResources().size()];
        String[] cpCmdList = new String[index.getResources().size()];
        List<String> chmodCmdList = new ArrayList<>();
        //一次性创建目录
        for (int i = 0; i < index.getResources().size(); i++) {
            ResourceInfo resource = index.getResources().get(i);
            createDirCmdList[i] = "mkdir -p " + resource.getTarget();
            cpCmdList[i] = "cp -rf " + TEMP_DIR + "/" + resource.getSource() + " " + resource.getTarget();

            //权限命令
            if (resource.isDir() && resource.isRecursive()) //如果是文件夹并且递归权限
                chmodCmdList.add("chmod -R " + resource.getPermissions() + " " + resource.getFullPath());
            else if (resource.isDir() && !resource.isRecursive()) { //如果是文件夹但是不递归权限
                //设置文件夹权限
                chmodCmdList.add("chmod " + resource.getPermissions() + " " + resource.getFullPath());
                //设置子级目录/文件权限
                chmodCmdList.add("chmod -R " + resource.getSubPermissions() + " " + resource.getFullPath() + "/*");
            } else if (!resource.isDir()) { //如果是文件
                chmodCmdList.add("chmod " + resource.getPermissions() + " " + resource.getFullPath());
            }
            System.out.println(resource.getFullPath());
        }
        System.out.println(index);
        boolean error = true;
        ShellUtil.CommandResult result = null;
        result = ShellUtil.execCommand(index.getMounts(), true, true); //首先挂载分区
        if (result.result == 0) {
            //执行创建目录命令
            result = ShellUtil.execCommand(createDirCmdList, true, true);
            if (result.result == 0) { //成功
                //执行复制命令
                result = ShellUtil.execCommand(cpCmdList, true, true);
                if (result.result == 0) { //执行授权命令
                    result = ShellUtil.execCommand(chmodCmdList, true, true);
                    if (result.result == 0) {
                        Toast.makeText(getActivity(), "全部成功!", Toast.LENGTH_LONG).show();
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
                                .setTitle("操作完成")
                                .setMessage("谷歌服务重启后生效，建议使用本程序的重启功能。是否立即重启？");
                        setAlertDialogButton(builder)
                                .create()
                                .show();
                        error = false;
                    }
                }
            }
        }
        if (error) {
            Toast.makeText(getActivity(), "很抱歉，有部分操作失败，程序马上进行回滚操作，请确认。", Toast.LENGTH_LONG).show();
        }


    }

    public void initVar() {
        CONF_PATH = FileUtils.createDirOnSDCard(CONF_NAME);
        TEMP_DIR = FileUtils.createDirOnSDCard(CONF_NAME + "/temp");//创建临时文件夹(存在则删除)
        //查找Views
        editPathInfo = (EditText) root.findViewById(R.id.editInfo);
        txtPagInfo = (TextView) root.findViewById(R.id.pagInfo);
        linkAbout = (TextView) root.findViewById(R.id.link_about);
        linkUpdate = (TextView) root.findViewById(R.id.link_update);
        //开始刷入按钮单击
        root.findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start(v);
            }
        });
        root.findViewById(R.id.btn_select).setOnClickListener(onSelectFileListener);
        editPathInfo.setOnClickListener(onSelectFileListener);

        setLink(linkAbout, linkUpdate);//设置文本链接可点击
        txtCurrentVersion = (TextView) root.findViewById(R.id.current_version);
        txtCurrentVersion.setText("当前版本:" + getCurVersion(getActivity()));
        //handlerMessage
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == WHAT_EDIT_INFO) {
                    editPathInfo.setHint(index.getModel() + ":" + index.getVersion());
                    txtPagInfo.setText(index.getInfo());
                }
            }
        };

        //读取临时文件夹
        readTempDir();
    }

    public void readTempDir() {
        BufferedReader reader = null;
        StringBuilder sb = null;
        File indexFile = new File(TEMP_DIR + "/" + INDEX_FILE);
        if (!indexFile.exists())
            return;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(indexFile)));
            String line = null;
            sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        index = (Index) JsonUtils.toObj(sb.toString(), Index.class);
        handler.sendEmptyMessage(WHAT_EDIT_INFO);
    }

    private AlertDialog.Builder setAlertDialogButton(final AlertDialog.Builder builder) {
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ShellUtil.execCommand("reboot", true);
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        return builder;
    }

    private void setLink(TextView... textView) {
        if (textView == null || textView.length <= 0)
            return;
        for (TextView text : textView) {
            text.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }

    public static String getCurVersion(Context context) {

        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo("io.bluerain.g4_tools", 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = packInfo.versionName;
        return version;
    }
}
